package com.gzw.shop.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gzw.shop.App;
import com.gzw.shop.Contans;
import com.gzw.shop.R;
import com.gzw.shop.adapter.FullyLinearLayoutManager;
import com.gzw.shop.adapter.WearOrderAdapter;
import com.gzw.shop.bean.Address;
import com.gzw.shop.bean.Charge;
import com.gzw.shop.bean.ShoppingCart;
import com.gzw.shop.http.OkHttpHelper;
import com.gzw.shop.http.SpotsCallBack;
import com.gzw.shop.msg.BaseRespMsg;
import com.gzw.shop.msg.CreateOrderRespMsg;
import com.gzw.shop.utils.CartProvider;
import com.gzw.shop.utils.JSONUtil;
import com.gzw.shop.widget.GToolbar;
import com.pingplusplus.android.PaymentActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Response;

public class CreateOrderActivity extends BaseActivity {


    @BindView(R.id.toolbar)
    GToolbar toolbar;
    @BindView(R.id.rl_addr)
    RelativeLayout rlAddr;
    @BindView(R.id.txt_order)
    TextView txtOrder;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.ll_items)
    LinearLayout llItems;
    @BindView(R.id.icon_alipay)
    ImageView iconAlipay;
    @BindView(R.id.rb_alipay)
    RadioButton rbAlipay;
    @BindView(R.id.rl_alipay)
    RelativeLayout rlAlipay;
    @BindView(R.id.icon_wechat)
    ImageView iconWechat;
    @BindView(R.id.rb_webchat)
    RadioButton rbWebchat;
    @BindView(R.id.rl_wechat)
    RelativeLayout rlWechat;
    @BindView(R.id.icon_bd)
    ImageView iconBd;
    @BindView(R.id.rb_bd)
    RadioButton rbBd;
    @BindView(R.id.rl_bd)
    RelativeLayout rlBd;
    @BindView(R.id.ll_pay)
    LinearLayout llPay;
    @BindView(R.id.txt_total)
    TextView txtTotal;
    @BindView(R.id.btn_createOrder)
    Button btnCreateOrder;
    @BindView(R.id.tv_namePhone)
    TextView tvNamePhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_Address)
    LinearLayout llAddress;

    /**
     * 微信支付渠道
     */
    private static final String CHANNEL_WECHAT = "wx";
    /**
     * 支付支付渠道
     */
    private static final String CHANNEL_ALIPAY = "alipay";
    /**
     * 百度支付渠道
     */
    private static final String CHANNEL_BFB = "bfb";

    private static String payChanner = CHANNEL_ALIPAY;

    private String orderNum;
    private float amount;

    private OkHttpHelper httpHelper = OkHttpHelper.getInstance();
    private CartProvider cartProvider;

    private WearOrderAdapter adapter;

    private Address address;


    @Override
    public int getLayoutId() {
        return R.layout.activity_create_order;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

        initAddress();
        showData();
    }

    private void initAddress() {

        Map<String, Object> params = new HashMap<>(1);
        params.put("user_id", App.getInstance().getUser().getId());

        httpHelper.get(Contans.API.ADDRESS_LIST, params, new SpotsCallBack<List<Address>>(this) {
            @Override
            public void onSuccess(Response response, List<Address> datas) {

                for (Address ad : datas) {
                    if (ad.getIsDefault()) {
                        address = ad;
                    }
                }
                if (address != null) {
                    showAddress(address);
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }


    private void showAddress(Address address) {
        tvAddress.setText(address.getAddr());
        tvNamePhone.setText(address.getConsignee() + "(" + replacePhone(address.getPhone()) + ")");
    }

    private String replacePhone(String phone) {
        return phone.substring(0, phone.length() - (phone.substring(3)).length()) + "****" + phone.substring(7);
    }

    @OnClick({R.id.rl_alipay, R.id.rl_bd, R.id.rl_wechat})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.rl_alipay:
                rbAlipay.setChecked(true);
                rbWebchat.setChecked(false);
                rbBd.setChecked(false);
                payChanner = CHANNEL_ALIPAY;
                break;
            case R.id.rl_bd:
                payChanner = CHANNEL_BFB;
                rbAlipay.setChecked(false);
                rbWebchat.setChecked(false);
                rbBd.setChecked(true);
                break;
            case R.id.rl_wechat:
                payChanner = CHANNEL_WECHAT;
                rbAlipay.setChecked(false);
                rbWebchat.setChecked(true);
                rbBd.setChecked(false);
                break;
        }
    }

    @OnClick(R.id.ll_Address)
    public void goToAddrsss() {
        Intent intent = new Intent(this, AddressListActivity.class);
        intent.putExtra("order", true);
        startActivityForResult(intent, Contans.REQUEST_CODE);
    }

    private void showData() {

        cartProvider = new CartProvider(this);
        if (adapter == null) {
            adapter = new WearOrderAdapter(this, cartProvider.getAll());

            FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(this);
            layoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(adapter);
        }

        amount = adapter.getTotalPrice();

        txtTotal.setText("应付款:￥" + amount);
    }

    @OnClick(R.id.btn_createOrder)
    public void CreateNewOrder() {

        postNewOrder();
    }

    private void postNewOrder() {
        final List<ShoppingCart> carts = adapter.getDatas();

        List<WareItem> items = new ArrayList<>(carts.size());
        for (ShoppingCart c : carts) {
            WareItem item = new WareItem(c.getId(), c.getPrice().intValue());
            items.add(item);
        }
        String item_json = JSONUtil.toJSON(items);
        Map<String, Object> params = new HashMap<>(5);
        params.put("user_id", App.getInstance().getUser().getId() + "");
        params.put("item_json", item_json);
        params.put("pay_channel", payChanner);
        params.put("amount", (int) amount + "");
        params.put("addr_id", 1 + "");

        btnCreateOrder.setEnabled(false);

        httpHelper.post(Contans.API.ORDER_CREATE, params, new SpotsCallBack<CreateOrderRespMsg>(this) {
            @Override
            public void onSuccess(Response response, CreateOrderRespMsg respMsg) {

                btnCreateOrder.setEnabled(true);
                orderNum = respMsg.getData().getOrderNum();
                Charge charge = respMsg.getData().getCharge();
                openPaymentActivity(JSONUtil.toJSON(charge));
            }

            @Override
            public void onError(Response response, int code, Exception e) {
                btnCreateOrder.setEnabled(true);
            }
        });

    }

    private void openPaymentActivity(String charge) {

        Intent intent = new Intent();
        String packageName = getPackageName();
        ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
        intent.setComponent(componentName);
        intent.putExtra(PaymentActivity.EXTRA_CHARGE, charge);
        startActivityForResult(intent, Contans.REQUEST_CODE_PAYMENT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Contans.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");

                if (result.equals("success"))
                    changeOrderStatus(1);
                else if (result.equals("fail"))
                    changeOrderStatus(-1);
                else if (result.equals("cancel"))
                    changeOrderStatus(-2);
                else
                    changeOrderStatus(0);

            /* 处理返回值
             * "success" - payment succeed
             * "fail"    - payment failed
             * "cancel"  - user canceld
             * "invalid" - payment plugin not installed
             *
             * 如果是银联渠道返回 invalid，调用 UPPayAssistEx.installUPPayPlugin(this); 安装银联安全支付控件。
             */
//                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
//                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息

            }
        } else if (requestCode == Contans.REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {

                if (data.getExtras() != null) {
                    Address address = (Address) data.getExtras().get("address");
                    showAddress(address);
                }
            }
        }
    }


    private void changeOrderStatus(final int status) {

        Map<String, Object> params = new HashMap<>(5);
        params.put("order_num", orderNum);
        params.put("status", status + "");


        httpHelper.post(Contans.API.ORDER_COMPLEPE, params, new SpotsCallBack<BaseRespMsg>(this) {
            @Override
            public void onSuccess(Response response, BaseRespMsg o) {

                toPayResultActivity(status);
            }

            @Override
            public void onError(Response response, int code, Exception e) {
                toPayResultActivity(-1);
            }
        });

    }


    private void toPayResultActivity(int status) {
        Intent intent = new Intent(this, PayResultActivity.class);
        intent.putExtra("status", status);
        startActivity(intent);
        this.finish();
    }

    class WareItem {
        private Long ware_id;
        private int amount;

        public WareItem(Long ware_id, int amount) {
            this.ware_id = ware_id;
            this.amount = amount;
        }

        public Long getWare_id() {
            return ware_id;
        }

        public void setWare_id(Long ware_id) {
            this.ware_id = ware_id;
        }

        public int getAmount() {
            return amount;
        }

        public void setAmount(int amount) {
            this.amount = amount;
        }
    }

}
